// 添加日志功能
async function shouldLog() {
    try {
        const { enableLogging = true } = await chrome.storage.sync.get('enableLogging');
        return enableLogging;
    } catch {
        return false;
    }
}

async function log(level, message, ...args) {
    if (await shouldLog()) {
        console[level](`[Form Persistence Background] ${message}`, ...args);
    }
}

// 安全地发送消息到标签页
async function sendMessageToTab(tabId, message) {
    try {
        // 首先检查标签页是否仍然存在
        const tab = await chrome.tabs.get(tabId).catch(() => null);
        if (!tab) {
            await log('warn', `标签页 ${tabId} 不存在，跳过发送消息`);
            return;
        }

        // 检查标签页URL是否合法
        if (!tab.url || (!tab.url.startsWith('http') && !tab.url.startsWith('https'))) {
            await log('debug', `标签页 ${tabId} URL不合法，跳过发送消息`);
            return;
        }

        // 尝试发送消息
        await chrome.tabs.sendMessage(tabId, message).catch(error => {
            if (error.message.includes('Could not establish connection')) {
                // 这是正常的情况，内容脚本可能还未加载
                log('debug', `标签页 ${tabId} 未准备好接收消息`);
            } else {
                log('warn', `发送消息到标签页 ${tabId} 失败:`, error);
            }
        });
    } catch (error) {
        await log('error', `处理标签页 ${tabId} 消息时出错:`, error);
    }
}

// 安全地发送消息到所有标签页
async function broadcastMessage(message) {
    try {
        const tabs = await chrome.tabs.query({});
        const sendPromises = tabs.map(tab => sendMessageToTab(tab.id, message));
        await Promise.allSettled(sendPromises);
    } catch (error) {
        await log('error', '广播消息失败:', error);
    }
}

// 安全地发送消息到运行时
async function sendRuntimeMessage(message) {
    try {
        await chrome.runtime.sendMessage(message).catch(error => {
            if (!error.message.includes('Could not establish connection')) {
                log('warn', '发送运行时消息失败:', error);
            }
        });
    } catch (error) {
        await log('error', '处理运行时消息失败:', error);
    }
}

// URL 匹配函数
function isUrlMatched(url, pattern) {
    if (!pattern || !url) return false;
    return url.includes(pattern);
}

// 检查 URL 是否在允许列表中
async function checkUrlPermission(url) {
    try {
        const { enabledUrls = [], disabledUrls = [] } = await chrome.storage.sync.get(['enabledUrls', 'disabledUrls']);
        
        // 首先检查是否在禁用列表中
        for (const pattern of disabledUrls) {
            if (isUrlMatched(url, pattern)) {
                return false;
            }
        }
        
        // 然后检查是否在启用列表中
        for (const pattern of enabledUrls) {
            if (isUrlMatched(url, pattern)) {
                return true;
            }
        }
        
        return false;
    } catch (error) {
        console.error('检查 URL 权限时出错:', error);
        return false;
    }
}

// 监听标签页刷新事件
chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
    if (changeInfo.status === 'complete' && tab.url) {
        // 延迟发送消息，确保内容脚本已加载
        setTimeout(() => {
            sendMessageToTab(tabId, { action: 'checkStatus' });
        }, 500);
    }
});

// 监听存储变化
chrome.storage.onChanged.addListener(async (changes, namespace) => {
    if (namespace === 'sync' && (changes.enabledUrls || changes.disabledUrls)) {
        await log('info', '检测到URL配置更改，通知所有标签页');
        
        // 通知所有标签页
        await broadcastMessage({ action: 'checkStatus' });
        
        // 通知选项页面
        await sendRuntimeMessage({ 
            action: 'optionsPageUpdate',
            data: changes
        });
    }
});

// 预加载所有语言文件
async function preloadLanguageFiles() {
    const locales = ['zh_CN', 'en'];
    try {
        for (const locale of locales) {
            const url = chrome.runtime.getURL(`_locales/${locale}/messages.json`);
            const response = await fetch(url);
            const messages = await response.json();
            
            // 保存到缓存
            await chrome.storage.local.set({
                [`i18n_${locale}`]: {
                    messages,
                    timestamp: Date.now()
                }
            });
            
            await log('info', `预加载语言文件成功: ${locale}`);
        }
    } catch (error) {
        await log('error', '预加载语言文件失败:', error);
    }
}

// 自动重新加载过期的语言文件
async function reloadExpiredLanguageFiles() {
    const locales = ['zh_CN', 'en'];
    const maxAge = 24 * 60 * 60 * 1000; // 24小时

    try {
        const cache = await chrome.storage.local.get(locales.map(locale => `i18n_${locale}`));
        const now = Date.now();

        for (const locale of locales) {
            const cacheKey = `i18n_${locale}`;
            const cachedData = cache[cacheKey];

            if (!cachedData || !cachedData.timestamp || (now - cachedData.timestamp) > maxAge) {
                await log('info', `重新加载过期的语言文件: ${locale}`);
                const url = chrome.runtime.getURL(`_locales/${locale}/messages.json`);
                const response = await fetch(url);
                const messages = await response.json();
                
                await chrome.storage.local.set({
                    [cacheKey]: {
                        messages,
                        timestamp: now
                    }
                });
            }
        }
    } catch (error) {
        await log('error', '重新加载语言文件失败:', error);
    }
}

// 设置当前语言
async function setLanguage() {
    try {
        const { language = 'zh_CN' } = await chrome.storage.sync.get('language');
        await log('info', `当前语言设置: ${language}`);
        
        // 尝试加载设置的语言文件
        const cacheKey = `i18n_${language}`;
        const cache = await chrome.storage.local.get(cacheKey);
        
        if (!cache[cacheKey]) {
            // 如果找不到设置的语言，回退到默认语言
            await log('warn', `未找到语言 ${language} 的缓存，回退到默认语言`);
            await chrome.storage.sync.set({ language: 'zh_CN' });
        }
    } catch (error) {
        await log('error', '获取语言设置失败:', error);
    }
}

// 在安装和更新时初始化语言设置
chrome.runtime.onInstalled.addListener(async ({ reason }) => {
    if (reason === 'install') {
        // 首次安装时使用浏览器语言或默认为中文
        const browserLang = navigator.language.toLowerCase();
        const defaultLang = browserLang.startsWith('zh') ? 'zh_CN' : 'en';
        await chrome.storage.sync.set({ language: defaultLang });
    }
    // 预加载所有语言文件
    await preloadLanguageFiles();
    // 应用语言设置
    await setLanguage();
});

// 在启动时应用语言设置并检查过期的语言文件
chrome.runtime.onStartup.addListener(async () => {
    await reloadExpiredLanguageFiles();
    await setLanguage();
});

// 监听语言更改消息
chrome.runtime.onMessage.addListener(async (message, sender, sendResponse) => {
    if (message.action === 'updateLanguage') {
        await log('info', `语言已更改为: ${message.language}`);

        // 通知所有标签页和扩展页面
        try {
            // 获取所有窗口中的所有标签页
            const windows = await chrome.windows.getAll({ populate: true });
            for (const window of windows) {
                for (const tab of window.tabs) {
                    try {
                        await chrome.tabs.sendMessage(tab.id, { 
                            action: 'updateLanguage',
                            language: message.language
                        });
                    } catch (error) {
                        // 忽略未加载内容脚本的标签页错误
                    }
                }
            }

            // 此消息会被弹窗和选项页面接收到
            chrome.runtime.sendMessage({ 
                action: 'updateLanguage',
                language: message.language,
                source: 'background'
            });
        } catch (error) {
            await log('error', '发送语言更新消息失败:', error);
        }
    }
});